package com.warrantyhotel.android.adapter;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.News_RSS;
import com.warrantyhotel.android.util.BitmapUtils;
import com.warrantyhotel.android.util.BitmapUtils.OnFetchCompleteListener;

public class NewsAdapter extends CursorAdapter {

	private LayoutInflater mInflater;

	public NewsAdapter(Context context, Cursor c) {
		super(context, c, false);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		final RssItemViewHolder listItem = (RssItemViewHolder) view.getTag();
		final String rssTitle = cursor.getString(cursor.getColumnIndex(News_RSS.TITLE));
		final String description = cursor.getString(cursor.getColumnIndex(News_RSS.DESCRIPTION));
		final String thumbnail = cursor.getString(cursor.getColumnIndex(News_RSS.LINK_THUMBNAIL));

		listItem.txtRssTitle.setText(rssTitle);

		BitmapUtils.fetchImage(context, thumbnail, new OnFetchCompleteListener() {

			@Override
			public void onFetchComplete(Object cookie, Bitmap result) {
				listItem.RssImage.setImageBitmap(result);
			}
		});
		int maxLength = 60;
		int descriptionLength = (description.length() < maxLength) ? description.length() : maxLength;
		String result;
		int index = description.indexOf("<");
		if (index != -1 && index < descriptionLength)
			result = description.substring(0, index);
		else
			result = description.substring(0, descriptionLength);

		listItem.txtRssDescription.setText(result.concat("..."));
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		View view = mInflater.inflate(R.layout.rss_item, null);
		final RssItemViewHolder listItem = new RssItemViewHolder();
		listItem.txtRssTitle = (TextView) view.findViewById(R.id.rss_title_item);
		listItem.txtRssDescription = (TextView) view.findViewById(R.id.rss_description_item);
		listItem.RssImage = (ImageView) view.findViewById(R.id.rss_thumbnail_item);
		view.setTag(listItem);
		return view;
	}

	public class RssItemViewHolder {
		TextView txtRssTitle;
		TextView txtRssDescription;
		ImageView RssImage;
	}

}
